package com.docMan.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;
import java.util.Map;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import com.docMan.dao.pojo.DocFtp;

public class FtpUtils {
	private static DocFtp docFtpOa=new DocFtp();
	public static boolean deleteDirectory(DocFtp docFtp,String path){
		boolean result=false;
		FTPClient ftp=new FTPClient();
		path=docFtp.getDiskName()+path;
		try {
			int reply;
			ftp.connect(docFtp.getServerName(), docFtp.getPort());
			ftp.login(docFtp.getUsername(), docFtp.getPassword());

			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return result;
			}
			ftp.setFileType(FTP.BINARY_FILE_TYPE);
			ftp.setControlEncoding("gbk");
			result=iterateDelete(ftp,getPath(path, "iso-8859-1"));
//			result=iterateDelete(ftp,path);
			ftp.logout();
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
					return result;
				} catch (IOException e) {
					e.printStackTrace();
					return false;
				}
			}
		}
		return result;
	}
	
	/** 
     *  
     *【功能描述：删除文件夹】 
     *【功能详细描述：功能详细描述】 
     * @see   【类、类#方法、类#成员】 
     * @param ftpClient 
     * @param ftpPath  文件夹的地址 
     * @return true 表似成功，false 失败 
     * @throws IOException 
     */  
    private static boolean iterateDelete(FTPClient ftpClient,String ftpPath) throws IOException{  
        FTPFile[] files = ftpClient.listFiles(ftpPath);  
        boolean flag = false;  
        for(FTPFile f:files){  
        	//TODO
            String path = ftpPath+File.separator+getPath(f.getName(),"iso-8859-1");  
//            String path = ftpPath+File.separator+f.getName();  
            if(f.isFile()){  
                // 是文件就删除文件  
                ftpClient.deleteFile(path);  
            }else if(f.isDirectory()){  
               iterateDelete(ftpClient,path);  
            }  
        }  
        // 每次删除文件夹以后就去查看该文件夹下面是否还有文件，没有就删除该空文件夹  
        FTPFile[] files2 = ftpClient.listFiles(ftpPath);   
        if(files2.length==0){  
            flag = ftpClient.removeDirectory(ftpPath);  
        }else{  
            flag = false;  
        }  
        return flag;  
    }  
	/**
	 * 在ftp上创建文件夹
	 * @param path
	 * @param docFtp
	 * @return
	 * @throws IOException 
	 */
	public static boolean makeDirectory(String path,DocFtp docFtp) throws IOException{
		boolean result=false;
		FTPClient ftp=new FTPClient();
		path=docFtp.getDiskName()+path;
		File file=new File(path);
		try {
			int reply;
			ftp.connect(docFtp.getServerName(), docFtp.getPort());
			ftp.login(docFtp.getUsername(), docFtp.getPassword());

			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return result;
			}
			ftp.setFileType(FTP.BINARY_FILE_TYPE);
			ftp.setControlEncoding("gbk");
			FTPFile[] files=ftp.listFiles();
			if(!ftp.changeWorkingDirectory(getPath(path, "iso-8859-1"))){
//			if(!ftp.changeWorkingDirectory(path)){
				if(!changeDirectory(file.getParentFile().getPath(), file.getName(), ftp)){
					return false;
				}
				result=true;
				return result;
			}
			ftp.logout();
			result = true;
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}
	/**
	 * 
	 * @param url
	 *            ftp路径
	 * @param username
	 * @param password
	 * @param filename
	 *            文件名
	 * @param path
	 *            ftp上的路劲
	 * @param in
	 *            输入流
	 * @return
	 */
	@Deprecated
	public static boolean uploadFile(String url, int port, String username,
			String password, String filename, String path, InputStream in) {
		boolean success = false;
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			ftp.connect(url, port);
			ftp.login(username, password);

			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return success;
			}
			ftp.setFileType(FTP.BINARY_FILE_TYPE);
			ftp.setControlEncoding("gbk");
			// System.out.println(ftp.makeDirectory(path));
			if (!changeDirectory(path, "", ftp)) {
				return false;
			}
			System.out.println("上传"
					+ ftp.storeFile(new String(filename.getBytes("gbk"),
							"iso-8859-1"), in));
			
			in.close();
			ftp.logout();
			success = true;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return success;
	}

	/**
	 * 对原来upload函数的重载，将ftp服务器相关的数据封装在XtServer对象中
	 * 
	 * @param xtServer
	 * @param filename
	 * @param path
	 * @param in
	 * @return
	 */
	public static boolean uploadFile(DocFtp xtServer, String filename,
			String path, InputStream in) {
		boolean success = false;
		FTPClient ftp = new FTPClient();
		path=xtServer.getDiskName().replace(" ", "")+path;
		File file=new File(path);
		try {
			int reply;
			ftp.connect(xtServer.getServerName(), xtServer.getPort());
			ftp.login(xtServer.getUsername(), xtServer.getPassword());

			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return success;
			}
			ftp.setFileType(FTP.BINARY_FILE_TYPE);
			ftp.setControlEncoding("gbk");
			// System.out.println(ftp.makeDirectory(path));
			if(!ftp.changeWorkingDirectory(getPath(path, "iso-8859-1"))){
				if(!changeDirectory(file.getParentFile().getPath(), file.getName(), ftp)){
					System.out.println("创建文件夹false");
					return false;
				}
				System.out.println(path);
				System.out.println("创建文件夹后"+ ftp.changeWorkingDirectory(getPath(path, "iso-8859-1")));
				System.out.println(ftp.changeToParentDirectory());
				System.out.println(ftp.changeToParentDirectory());
				System.out.println(ftp.changeWorkingDirectory(path));
				System.out.println(ftp.changeWorkingDirectory(getPath(path, "iso-8859-1")));
			}
			FTPFile[] files= ftp.listFiles();
			System.out.println("上传"
					+ ftp.storeFile(new String(filename.getBytes("gbk"),
							"iso-8859-1"), in));
			in.close();
			ftp.logout();
			success = true;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return success;
	}
	
	/**
	 * 返回支持中文的的编码路径
	 * @param path
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	private static String getPath(String path,String encodeingType) throws UnsupportedEncodingException{
		return new String(path.getBytes("gbk"),encodeingType);
	}
	/**
	 * 对ftp的changeWorkingDirectory 进行封装，切换工作区时如果文件夹为创建，就递归的创建文件夹
	 * 
	 * @param pathParent
	 *            父文件夹路径
	 * @param directoryName
	 *            要创建的文件夹,pathParent下不想创建新的文件加，此参数可以为“”
	 * @param ftpClient
	 *            ftp
	 * @return
	 * @throws IOException
	 */
	public static boolean changeDirectory(String pathParent,
			String directoryName, FTPClient ftpClient) throws IOException {
		File file = new File(pathParent);
		if (!ftpClient.changeWorkingDirectory(getPath(pathParent, "iso-8859-1"))) {
			changeDirectory(file.getParentFile().getPath(), file.getName(),
					ftpClient);
		} else {
			ftpClient.changeWorkingDirectory(getPath(pathParent, "iso-8859-1"));
			ftpClient.makeDirectory(getPath(directoryName, "iso-8859-1"));
		}
		ftpClient.changeWorkingDirectory(getPath(pathParent, "iso-8859-1"));
		ftpClient.makeDirectory(getPath(directoryName, "iso-8859-1"));
		/*if (!ftpClient.changeWorkingDirectory(new String(pathParent.getBytes(),"iso-8859-1"))) {
			changeDirectory(file.getParentFile().getPath(), file.getName(),
					ftpClient);
		} else {
			ftpClient.changeWorkingDirectory(getPath(pathParent, "iso-8859-1"));
			ftpClient.makeDirectory(getPath(directoryName, "iso-8859-1"));
		}
		ftpClient.changeWorkingDirectory(getPath(pathParent, "iso-8859-1"));
		ftpClient.makeDirectory(getPath(directoryName, "iso-8859-1"));
		*/
		return true;
	}
	
	/**
	 * 
	 * @param url
	 *            ftp地址
	 * @param port
	 *            端口
	 * @param username
	 *            ftp的用户名
	 * @param password
	 *            ftp的用户名密码
	 * @param filename
	 *            要下在的文件名
	 * @param remotePath
	 *            文件在ftp上的存放路径
	 * @param localPath
	 *            下载到本地的路径
	 * @return
	 */
	@Deprecated
	public static boolean downloadFile(String url, int port, String username,
			String password, String filename, String remotePath,
			String localPath) {
		boolean success = false;
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			ftp.connect(url, port);
			ftp.login(username, password);
			ftp.setFileType(FTP.BINARY_FILE_TYPE);
			ftp.setControlEncoding("gbk");
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return success;
			}
			FTPFile[] filess = ftp.listFiles();

			boolean res = ftp.changeWorkingDirectory(remotePath.replace("//",
					"/"));
			System.out.println(res);
			FTPFile[] files = ftp.listFiles();
			int i = 0;
			for (FTPFile ftpFile : files) {
				if (ftpFile.getName().equals(filename)) {
					System.out.println(ftpFile.getName());
					File locaFile = new File(localPath + "/" + filename);
					if (!locaFile.getParentFile().exists())
						locaFile.getParentFile().mkdirs();
					OutputStream out = new FileOutputStream(locaFile);
					// 注意此处retrieveFile的第一个参数由gbk转为ISO-8859-1编码。否则下载后的文件内容为空。
					// 原因可能是由于aix系统默认的编码为ISO-8859-1
					ftp.retrieveFile(
							new String(ftpFile.getName().getBytes("gbk"),
									"ISO-8859-1"), out);
					out.close();
					success = true;
				}
				i++;
			}
			ftp.logout();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			System.err.println("文件不存在");
			return false;
		} catch (IOException e) {
			System.err.println("连接出现错误,文件读取错误");
			return false;
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return success;

	}
	/**
	 * 对原downloadFile函数的重载，将ftp相关参数封装在XtServer对象中
	 * @param xtServer
	 * @param filename
	 * @param remotePath
	 * @param localPath
	 * @return
	 */
	public static boolean downloadFile(DocFtp xtServer, String filename,
			String remotePath, String localPath) {
		boolean success = false;
		remotePath=xtServer.getDiskName().replace(" ", "")+remotePath;
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			ftp.connect(xtServer.getServerName().trim(), xtServer.getPort());
			ftp.login(xtServer.getUsername(), xtServer.getPassword());
			System.out.println(FTP.BINARY_FILE_TYPE);
			ftp.setFileType(FTP.BINARY_FILE_TYPE);
			ftp.setControlEncoding("gbk");
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return success;
			}
			
//			FTPFile[] filess = ftp.listFiles();
			boolean res = ftp.changeWorkingDirectory(getPath(remotePath.replace("//",
					"/"), "iso-8859-1"));
			/*boolean res1 = ftp.changeWorkingDirectory(getPath(remotePath.replace("//",
					"/"),"gbk"));
			boolean res2 = ftp.changeWorkingDirectory(getPath(remotePath.replace("//",
					"/"),"gbk"));
			boolean res3 = ftp.changeWorkingDirectory(remotePath.replace("//",
					"/"));*/
			System.out.println(res);
			FTPFile[] files = ftp.listFiles();
			int i = 0;
			for (FTPFile ftpFile : files) {
				if (ftpFile.getName().toLowerCase().equals(filename.toLowerCase())) {
					System.out.println(ftpFile.getName());
					File locaFile = new File(localPath + "/" + filename);
					if (!locaFile.getParentFile().exists())
						locaFile.getParentFile().mkdirs();
					OutputStream out = new FileOutputStream(locaFile);
					// 注意此处retrieveFile的第一个参数由gbk转为ISO-8859-1编码。否则下载后的文件内容为空。
					// 原因可能是由于aix系统默认的编码为ISO-8859-1
					ftp.retrieveFile(
							new String(ftpFile.getName().getBytes("gbk"),
									"ISO-8859-1"), out);
					out.close();
					success = true;
					System.out.println("成功下载文件"+filename+"远程路径为:"+remotePath+"服务器路径："+localPath);
				}
				i++;
			}
			ftp.logout();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			System.err.println("文件不存在");
			return false;
		} catch (IOException e) {
			System.err.println("连接出现错误,文件读取错误");
			return false;
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return success;

	}

	
	
	/**
	 * 获取登入后的ftpclient
	 * 
	 * @param url
	 * @param port
	 * @param username
	 * @param password
	 * @return
	 * @throws SocketException
	 * @throws IOException
	 */
	public static FTPClient loginFtp(String url, int port, String username,
			String password) throws SocketException, IOException {
		FTPClient ftp = new FTPClient();
		ftp.connect(url, port);
		ftp.login(username, password);
		ftp.setFileType(FTP.BINARY_FILE_TYPE);
		//ftp.setControlEncoding("gbk");
		int reply = ftp.getReplyCode();
		if (!FTPReply.isPositiveCompletion(reply)) {
			ftp.disconnect();
			return null;
		}
		return ftp;
	}

	/**
	 * 从ftp上复制文件到ftp上
	 * 
	 * @param urlFrom
	 * @param portFrom
	 * @param usernameFrom
	 * @param passwordFrom
	 * @param pathFrom
	 * @param fileFrom
	 * @param url2
	 * @param port2
	 * @param username2
	 * @param password2
	 * @param path2
	 * @param file2
	 * @return
	 * @throws IOException
	 * @throws SocketException
	 */
	@Deprecated
	public static boolean moveFileFromFtp2Ftp(String urlFrom, int portFrom,
			String usernameFrom, String passwordFrom, String pathFrom,
			String fileFromName, String url2, int port2, String username2,
			String password2, String path2, String file2Name)
			throws SocketException, IOException {
		String localPath = FinalConfig.FTP_TEMP_DOWNLOAD_PATH
				+ System.currentTimeMillis() + "/";
		if (!downloadFile(urlFrom, portFrom, usernameFrom, passwordFrom,
				fileFromName, pathFrom, localPath)) {
			return false;
		}
		FileInputStream in = new FileInputStream(new File(localPath
				+ fileFromName));
		if (!uploadFile(url2, port2, username2, password2, file2Name, path2, in)) {
			return false;
		}
		in.close();
		return true;
	}
	/**
	 * 从ftp上复制文件到ftp上
	 * @param xtServerFrom
	 * @param pathFrom
	 * @param fileFromName
	 * @param xtServer2
	 * @param path2
	 * @param file2Name
	 * @return
	 * @throws IOException
	 */
	public static boolean moveFileFromFtp2Ftp(DocFtp xtServerFrom,String pathFrom,String fileFromName,DocFtp xtServer2,String path2,String file2Name) throws IOException{
		String localPath = FinalConfig.FTP_TEMP_DOWNLOAD_PATH
				+ System.currentTimeMillis() + "/";
		if (!downloadFile(xtServerFrom, fileFromName, pathFrom, localPath)) {
			return false;
		}
		FileInputStream in = new FileInputStream(new File(localPath
				+ fileFromName));
		if (!uploadFile(xtServer2, file2Name, path2, in)) {
			return false;
		}
		in.close();
		return true;
	}
	
	public static String moveFileFromFtp2FtpSize(DocFtp xtServerFrom,String pathFrom,String fileFromName,DocFtp xtServer2,String path2,String file2Name) throws IOException{
		String localPath = FinalConfig.FTP_TEMP_DOWNLOAD_PATH
				+ System.currentTimeMillis() + "/";
		if (!downloadFile(xtServerFrom, fileFromName, pathFrom, localPath)) {
			return "0";
		}
		FileInputStream in = new FileInputStream(new File(localPath
				+ fileFromName));
		if (!uploadFile(xtServer2, file2Name, path2, in)) {
			return "0";
		}
		in.close();
		FileInputStream inSize = new FileInputStream(new File(localPath
				+ fileFromName));
		
		String fileSize=MathUtil.fileSize(inSize.available());
		inSize.close();
		return fileSize;
	}
	
	/**
	 * 从服务器本地上复制文件到ftp
	 * 
	 * @param localPath
	 *            文件在服务器上的路劲
	 * @param url
	 *            ftp地址
	 * @param port
	 *            端口
	 * @param username
	 * @param password
	 * @param path
	 *            ftp上要保存的路劲
	 * @return
	 * @throws IOException
	 */
	public static boolean movelocalFile2Ftp(String localPath, String url,
			int port, String username, String password, String path)
			throws IOException {
		String filename = "";
		filename = localPath.substring(localPath.lastIndexOf("\\") + 1,
				localPath.length());
		FileInputStream in = new FileInputStream(new File(localPath));
		if (uploadFile(url, port, username, password, filename, path, in)) {
			in.close();
			return true;
		}
		return false;
	}
	/**
	 * 从服务器本地上复制文件到ftp
	 * @param xtServer2
	 * @param localPath 文件在服务器上的路劲
	 * @param path  在ftp上要保存的路劲
	 * @return
	 * @throws IOException
	 */
	public static boolean movelocalFile2Ftp(DocFtp xtServer2,String localPath,String path) throws IOException{
		String filename = "";
		filename = localPath.substring(localPath.lastIndexOf("\\") + 1,
				localPath.length());
		FileInputStream in = new FileInputStream(new File(localPath));
		if (uploadFile(xtServer2, filename, path, in)) {
			in.close();
			return true;
		}
		return false;
	}
	
	public static boolean removeFile(DocFtp xtServer,String path){
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			ftp.connect(xtServer.getServerName().trim(), xtServer.getPort());
			ftp.login(xtServer.getUsername(), xtServer.getPassword());
			ftp.setFileType(FTP.BINARY_FILE_TYPE);
			ftp.setControlEncoding("gbk");
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return false;
			}
			System.out.println("删除文件"+path+" 结果"+ftp.deleteFile(getPath(path, "iso-8859-1")));
//			System.out.println("删除文件"+path+" 结果"+ftp.deleteFile(path));
		} catch (Exception exception) {
			exception.printStackTrace();
		}finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return true;
	}
	public static String getFtpFileName(String filePath){
		String fileName="";
		//文件名，以tif结尾的,路径的分隔符可能是/和\\两种情况,应为有/doc0801/C07173\00000001.TIF 所以要根据这两个符号位置蓝判断
		int loc1 = filePath.lastIndexOf("/");
		int loc2 =filePath.lastIndexOf("\\");
		if(loc1>loc2){
			//路径的开头分带/和不带/的路径分隔符是\，开头不带分隔符\
			fileName= filePath.substring(loc1+1,filePath.length());
		}else {
			fileName=filePath.substring(loc2+1,filePath.length());
		}
		return fileName;
	}
	public static String getPathPre(String filePath){
		String fileName="";
		//文件名，以tif结尾的,路径的分隔符可能是/和\\两种情况,应为有/doc0801/C07173\00000001.TIF 所以要根据这两个符号位置蓝判断
		int loc1 = filePath.lastIndexOf("/");
		int loc2 =filePath.lastIndexOf("\\");
		if(loc1>loc2){
			//路径的开头分带/和不带/的路径分隔符是\，开头不带分隔符\
			fileName= filePath.substring(0,loc1+1);
		}else {
			fileName=filePath.substring(0,loc2+1);
		}
		return fileName;
	}

	
	public static FTPFile[] getDirectoryFiles(DocFtp  xtServer,String path) throws Exception{
		boolean success = false;
		FTPClient ftp = new FTPClient();
		path=xtServer.getDiskName().trim()+path;
		File file=new File(path);
		try {
			int reply;
			ftp.connect(xtServer.getServerName(), xtServer.getPort());
			ftp.login(xtServer.getUsername(), xtServer.getPassword());

			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				throw new Exception();
			}
			ftp.setFileType(FTP.BINARY_FILE_TYPE);
			ftp.setControlEncoding("gbk");
			// System.out.println(ftp.makeDirectory(path));
			if(!ftp.changeWorkingDirectory(getPath(path, "ISO-8859-1"))){
				throw new Exception();
			}
			FTPFile[] files= ftp.listFiles();
			ftp.logout();
			success = true;
			return files;
		} catch (IOException e) {
			e.printStackTrace();
			throw new Exception();
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException e) {
					e.printStackTrace();
					throw new Exception();
				}
			}
		}
	}
	
	public static DocFtp getOaFtp() throws FileNotFoundException, UnsupportedEncodingException{
		String filePath="config.properties";
		Map<String, String> props=PropsUtil.loadPropsToMap(filePath);
		docFtpOa.setIp(props.get("oa.ftp.url"));
		docFtpOa.setServerName(props.get("oa.ftp.url"));
		docFtpOa.setUsername(props.get("oa.ftp.username"));
		docFtpOa.setPassword(props.get("oa.ftp.password"));
		docFtpOa.setDiskName(props.get("oa.ftp.diskname"));
		docFtpOa.setPort(CastUtil.castInt(props.get("oa.ftp.port")));
		return docFtpOa;
	}
	/**
	 * 复制文件
	 * @param docFtp
	 * @param fileName
	 * @param sourePath
	 * @param toPath
	 * @return
	 * @throws IOException 
	 */
	public static boolean copyFile(DocFtp docFtp,String fileName,String sourePath,String toPath) throws IOException{
		ByteArrayInputStream in=null;
		ByteArrayOutputStream fos=new ByteArrayOutputStream();
		boolean success = false;
		sourePath=docFtp.getDiskName().trim()+sourePath;
		toPath=docFtp.getDiskName().trim()+toPath;
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			ftp.connect(docFtp.getServerName().trim(), docFtp.getPort());
			ftp.login(docFtp.getUsername(), docFtp.getPassword());
			System.out.println(FTP.BINARY_FILE_TYPE);
			ftp.setFileType(FTP.BINARY_FILE_TYPE);
			ftp.setControlEncoding("gbk");
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return success;
			}
			boolean res = ftp.changeWorkingDirectory(getPath(sourePath.replace("//",
					"/"), "iso-8859-1"));
			System.out.println(ftp.retrieveFile(new String(fileName.getBytes("gbk"),
					"iso-8859-1"), fos));
			in=new ByteArrayInputStream(fos.toByteArray());
			if(in!=null){
				System.out.println(ftp.changeWorkingDirectory(getPath(toPath.replace("//",
						"/"), "iso-8859-1")));
				boolean res1 = ftp.changeWorkingDirectory(getPath(toPath.replace("//",
						"/"),"gbk"));
				boolean res2 = ftp.changeWorkingDirectory(getPath(toPath.replace("//",
						"/"),"gbk"));
				System.out.println(ftp.storeFile(new String(fileName.getBytes("gbk"), "iso-8859-1"), in));  
			}
		}catch(IOException exception){
			exception.printStackTrace();
		}finally{
			// 关闭流  
	        if (in != null) {  
	            in.close();  
	        }  
	        if (fos != null) {  
	            fos.close();  
	        }  
	        ftp.disconnect();
		}
		return true;
	}
	public  static boolean hasFile(DocFtp docFtp,String remotePath,String fileName) {
		boolean success = false;
		remotePath=docFtp.getDiskName().trim()+remotePath;
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			ftp.connect(docFtp.getServerName().trim(), docFtp.getPort());
			ftp.login(docFtp.getUsername(), docFtp.getPassword());
			System.out.println(FTP.BINARY_FILE_TYPE);
			ftp.setFileType(FTP.BINARY_FILE_TYPE);
			ftp.setControlEncoding("gbk");
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return success;
			}
			boolean res = ftp.changeWorkingDirectory(getPath(remotePath.replace("//",
					"/"), "iso-8859-1"));
			System.out.println(res);
			FTPFile[] files = ftp.listFiles();
			for (FTPFile ftpFile : files) {
				if (ftpFile.getName().toLowerCase().equals(fileName.toLowerCase())) {
					success = true;
				}
			}
			ftp.logout();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			System.err.println("文件不存在");
			return false;
		} catch (IOException e) {
			System.err.println("连接出现错误,文件读取错误");
			return false;
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return success;

	}
}
